package dk.mirasola.systemtraining.bridgewidgets.client.ui.editor;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.LeafValueEditor;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import dk.mirasola.systemtraining.bridgewidgets.client.ui.RenderUtil;
import dk.mirasola.systemtraining.bridgewidgets.shared.model.Seat;

import java.util.HashSet;
import java.util.Set;

public class SeatsEditor extends Composite implements LeafValueEditor<Set<Seat>> {
    interface SeatsEditorUIBinder extends UiBinder<Widget, SeatsEditor> {
    }

    private static SeatsEditorUIBinder uiBinder = GWT.create(SeatsEditorUIBinder.class);

    @UiField
    CheckBox north;
    @UiField
    CheckBox east;
    @UiField
    CheckBox south;
    @UiField
    CheckBox west;

    public SeatsEditor() {
        initWidget(uiBinder.createAndBindUi(this));
        north.setHTML(RenderUtil.renderSeatUppercaseFirst(Seat.NORTH));
        east.setHTML(RenderUtil.renderSeatUppercaseFirst(Seat.EAST));
        south.setHTML(RenderUtil.renderSeatUppercaseFirst(Seat.SOUTH));
        west.setHTML(RenderUtil.renderSeatUppercaseFirst(Seat.WEST));
    }

    @Override
    public void setValue(Set<Seat> seats) {
        if (seats == null) {
            throw new NullPointerException();
        }
        north.setValue(seats.contains(Seat.NORTH));
        east.setValue(seats.contains(Seat.EAST));
        south.setValue(seats.contains(Seat.SOUTH));
        west.setValue(seats.contains(Seat.WEST));
    }

    public Set<Seat> getValue() {
        Set<Seat> seats = new HashSet<Seat>();
        if (north.getValue()) {
            seats.add(Seat.NORTH);
        }
        if (east.getValue()) {
            seats.add(Seat.EAST);
        }
        if (south.getValue()) {
            seats.add(Seat.SOUTH);
        }
        if (west.getValue()) {
            seats.add(Seat.WEST);
        }
        return seats;
    }
}
